//
//  FollowUpViewController.m
//  EMMApp
//
//  Created by Mac on 16/5/19.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "FollowUpViewController.h"
#import "KnowDetailCell.h"
#import "RecordView.h"
#import "AddFollowApi.h"
#import "GetFollowListApi.h"
#import "FollowOneCell.h"
#import "FollowTwoCell.h"
#import "FollowThreeCell.h"
#import "NSString+Base64.h"
#import "NSData+Base64.h"
#import <AVFoundation/AVFoundation.h>
#import "QBImagePickerController.h"

#import "NSString+Base64.h"
#import "NSData+Base64.h"
#import "EditMemberInfoApi.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "VGReturnPartPicViewCell.h"
#import "MenuLitsView.h"
#import "EMMImageView.h"
#import "MHPhotoBrowserController.h"
#import "lame.h"
#import "FSAudioStream.h"

#import "UUInputFunctionView.h"
#import "EditFollowApi.h"



@interface FollowUpViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,AVAudioPlayerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,QBImagePickerControllerDelegate,UUInputFunctionViewDelegate> {
 
    NSMutableDictionary *dic;//存对应的数据
    NSMutableArray *selectedArr;//二级列表是否展开状态
    NSMutableArray *titleDataArray;
    NSArray *dataArray;//数据源，显示每个cell的数据
    NSMutableDictionary *stateDic;//三级列表是否展开状态
    NSMutableArray *grouparr0;
    BOOL _isfollow;
    BOOL _isly;
    NSString *index;
    NSString *followString;
    BOOL _isBoy;
    NSString *boy;
    UUInputFunctionView *source;
}

@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//音频播放器，用于播放录音文件

@property (nonatomic, strong) UITableView *knowDtailTableView;

@property (nonatomic, strong) UIView *followUpView;

@property (nonatomic, strong) UITextField *followTextField;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) AVAudioPlayer *player;

@property(nonatomic,strong) NSMutableArray* picArray;

@property (nonatomic, strong) MenuLitsView *menu;

@property (nonatomic,strong) FSAudioStream *audioStream;

@property (nonatomic,strong) PlayAnimationView *playView;

@property (nonatomic, strong) GetCustomerDetail *getCustomerDetail;//详情Model
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameWidthConst;

@end

@implementation FollowUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArr = [[NSMutableArray alloc] init];
    [self showHudInWindow:@"正在加载请稍等..."];
    [self postGetFollowListApi];
    [self creatNavigationController];
    index  = @"0";
    followString = @"1";
    _isBoy = YES;
    _picArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    dic = [[NSMutableDictionary alloc] init];
    selectedArr = [[NSMutableArray alloc] init];
    dataArray = [[NSArray alloc] init];
    NSInteger h = 0;
    if ([NSString isStringEmpty2:self.followId] == NO) {
        h = 150;
    }else {
        h = 100;
    }
    _knowDtailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 120, EMM_WIDTH, EMM_HEIGHT-120-h-SafeAreaTopHeight) style:UITableViewStylePlain];
    _knowDtailTableView.delegate = self;
    _knowDtailTableView.dataSource = self;
    _knowDtailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _knowDtailTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_knowDtailTableView];
    [self creatInitWithFunctionShowUI];
    [self initDataSource];
    [self.phoneSDetailsbtn addTarget:self action:@selector(phoneSDetailsbtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.audioStream play];
    
    //注册键盘出现的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘消失的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backPushNotification:) name:@"isBackPushNotification" object:nil];
}

- (void)backPushNotification:(NSNotification *)notification {
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    [self postGetCustomerDetailApi];
}


#pragma mark - 查询客户详情api
- (void)postGetCustomerDetailApi {
    GetCustomerDetailApi *api = [[GetCustomerDetailApi alloc] initWithCustomerId:self.customerId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetCustomerDetailApi *result = (GetCustomerDetailApi *)request;
        if (result.isSuccess) {
            GetCustomerDetail *get = result.resultData;
            _getCustomerDetail = get;
            if ([NSString isStringEmpty2:get.customerStar] == NO) {
                if ([get.customerStar isEqualToString:@"是"]) {
                    self.customerStar.hidden = NO;
                    self.sexLabel.layer.masksToBounds = YES;
                    self.sexLabel.layer.cornerRadius = 5;
                    self.sexLabel.backgroundColor = [UIColor colorFromHexCode:@"#f7653e"];
                    if ([get.customerSex isEqualToString:@"1"]) {
                        self.sexLabel.text = @"男";
                    }else if ([get.customerSex isEqualToString:@"2"]) {
                        self.sexLabel.text = @"女";
                    }else if ([get.customerSex isEqualToString:@"男"]) {
                        self.sexLabel.text = get.customerSex;
                    }else if ([get.customerSex isEqualToString:@"女"]) {
                        self.sexLabel.text = get.customerSex;
                    }
                    self.gradeLabel.layer.masksToBounds = YES;
                    self.gradeLabel.layer.cornerRadius = 5;
                    self.gradeLabel.text = get.intentionLevel;
                    self.gradeLabel.backgroundColor = [UIColor colorFromHexCode:@"#f82b49"];
                    
                }else {
                    self.customerStar.hidden = YES;
                    self.sex1Label.layer.masksToBounds = YES;
                    self.sex1Label.layer.cornerRadius = 5;
                    self.sex1Label.backgroundColor = [UIColor colorFromHexCode:@"#f7653e"];
                    if ([get.customerSex isEqualToString:@"1"]) {
                        self.sex1Label.text = @"男";
                    }else if ([get.customerSex isEqualToString:@"2"]) {
                        self.sex1Label.text = @"女";
                    }else if ([get.customerSex isEqualToString:@"男"]) {
                        self.sex1Label.text = get.customerSex;
                    }else if ([get.customerSex isEqualToString:@"女"]) {
                        self.sex1Label.text = get.customerSex;
                    }
                    self.grade1Label.layer.masksToBounds = YES;
                    self.grade1Label.layer.cornerRadius = 5;
                    self.grade1Label.text = get.intentionLevel;
                    self.grade1Label.backgroundColor = [UIColor colorFromHexCode:@"#f82b49"];
                    
                }
            }
            self.userNameLabel.text = get.customerName;
            self.phoneLabel.text = get.customerPhone;
            self.kfLabel.text = get.customerOrigin;
            self.kfLabel.textColor = [UIColor colorFromHexCode:@"#ff7200"];
            self.qyLabel.text = get.customerStatus;
            self.qyLabel.textColor = [UIColor colorFromHexCode:@"#ff7200"];
            
            CGFloat width = self.view.frame.size.width - 150;
            NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15],};
            CGSize textSize = [get.customerName boundingRectWithSize:self.view.frame.size options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
            if (textSize.width > width ) {
                self.nameWidthConst.constant = width;
            }else {
                self.nameWidthConst.constant = textSize.width + 10;
            }
            
        } else {
            //            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_knowDtailTableView reloadData];
        //        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        //        [self hideHud];
    }];
}


#pragma mark -
- (void)postGetFollowListApi{

    [_dataArr removeAllObjects];
    GetFollowListApi *api = [[GetFollowListApi alloc] initWithCustomerId:self.customerId];
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetFollowListApi *result = (GetFollowListApi *)request;
        if (result.isSuccess) {
            GetFollowList *get = result.resultData;
            for (FollowList *list in get.followList) {
                [_dataArr addObject:list];
            }
            [_knowDtailTableView reloadData];
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"添加跟进";
//    [self configLeftBtn];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 54 ,44)];
    [backBtn addTarget:self
                action:@selector(followBtnClick:)
      forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"ico_back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    if (EMM_WIDTH <= 320) {
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }else if (EMM_WIDTH > 375){
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    }else{
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_jia"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(KnowRightClick:)];
    [self.navigationItem setRightBarButtonItem:rightItme];

}

- (void)followBtnClick:(UIButton *)btn {
    [self creatRemoveFromSuperview];
    if (_followUpViewBlock) {
        _followUpViewBlock();
    }
    if ([NSString isStringEmpty2:@"1"]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)creatRemoveFromSuperview {
    [_menu removeFromSuperview];
    _menu = nil;
}

#pragma mark - 导航右按钮选择响应事件
/**
 *  功能描述：
 *  弹出选择跟进的方式
 *  创建时间：16/5/19
 *
 *  更新时间：2017/02/17 下午
 *  更新人： wangguiping
 *  将 “到访” 改为 “拜访”
 */
- (void)KnowRightClick:(UIButton *)btn  {
    NSArray *arr = [NSArray arrayWithObjects:@"来电",@"来访",@"信息",@"去电",@"拜访",@"微信", nil];
    _menu = [[MenuLitsView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) items:arr indet:index isShowUI:NO guodu:arr.count * 50];
    _menu.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:_menu];
    __weak MenuLitsView *weakSelf = _menu;
    [weakSelf setMenuLitsBlock:^(NSString *title, NSString *indet) {
        
        if ([NSString isStringEmpty2:indet] == NO) {
            index = indet;
            if ([title isEqualToString:@"微信"]) {
                followString = @"7";
            }else {
                followString = [NSString stringWithFormat:@"%ld",[indet integerValue]+1];
            }
        }
        [weakSelf removeFromSuperview];
    }];
}

- (void)creatInitWithFunctionShowUI {
    NSInteger h = 0;
    NSInteger h1 = 0;
    if ([NSString isStringEmpty2:self.followId] == NO) {
        h = 140;
        h1 = 50;
    }else {
        h = 100;
        h1 = 10;
    }
    _followUpView = [[UIView alloc] initWithFrame:CGRectMake(0, EMM_HEIGHT-SafeAreaTopHeight-h, EMM_WIDTH, h)];
    _followUpView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_followUpView];
    UIView *v1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 0.5)];
    v1.backgroundColor = [UIColor lightGrayColor];
    [_followUpView addSubview:v1];

    UILabel *wjtLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 80, 20)];
    wjtLabel.font = [UIFont systemFontOfSize:15];
    wjtLabel.text = @"快速跟进:";
    wjtLabel.textColor = [UIColor colorFromHexCode:@"#5A5A5A"];
    
    UIButton *wjtBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    wjtBtn.frame = CGRectMake(90, 10, 80, 30);
    wjtBtn.backgroundColor = [UIColor whiteColor];
    [wjtBtn setTitle:@"未接通" forState:UIControlStateNormal];
    wjtBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [wjtBtn setTitleColor:[UIColor colorFromHexCode:@"#5A5A5A"] forState:UIControlStateNormal];
    wjtBtn.layer.masksToBounds = YES;
    wjtBtn.layer.cornerRadius = 5;
    wjtBtn.layer.borderWidth = 0.5;
    wjtBtn.layer.borderColor = [[UIColor colorFromHexCode:@"#CCCCCC"] CGColor];
    [wjtBtn addTarget:self action:@selector(wjtBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    if ([NSString isStringEmpty2:self.followId] == NO) {
        [_followUpView addSubview:wjtBtn];
        [_followUpView addSubview:wjtLabel];
    }
    
    _followTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, h1, EMM_WIDTH-30, 40)];
    _followTextField.delegate = self;
    [_followTextField setBorderStyle:UITextBorderStyleRoundedRect];
    _followTextField.returnKeyType =UIReturnKeySend;
    _followTextField.placeholder = @"请填写跟进内容";
    [_followUpView addSubview:_followTextField];
    
    
    UIView *View = [[UIView alloc] initWithFrame:CGRectMake(0, _followTextField.frame.size.height+h1+5, EMM_WIDTH, 170)];
    View.backgroundColor = [UIColor whiteColor];
    [_followUpView addSubview:View];
    
    UIButton *lyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    lyBtn.frame = CGRectMake((EMM_WIDTH/3-40)/2, 0, 40, 40);
    [lyBtn setImage:[[UIImage imageNamed:@"btn_say"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [lyBtn addTarget:self action:@selector(lyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [View addSubview:lyBtn];
    
    UIButton *xjBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    xjBtn.frame = CGRectMake(EMM_WIDTH/3+(EMM_WIDTH/3-40)/2, 0, 40, 40);
    [xjBtn setImage:[[UIImage imageNamed:@"btn_photo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [xjBtn addTarget:self action:@selector(xjBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [View addSubview:xjBtn];
    
    UIButton *xcBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    xcBtn.frame = CGRectMake(EMM_WIDTH/3+EMM_WIDTH/3+(EMM_WIDTH/3-40)/2,0, 40, 40);
    [xcBtn setImage:[[UIImage imageNamed:@"btn_pict"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [xcBtn addTarget:self action:@selector(xcBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [View addSubview:xcBtn];
    
    source = [[UUInputFunctionView alloc] initWithSuperVC:self];
    source.frame = CGRectMake((EMM_WIDTH-70)/2, 60, 70, 70);
    source.delegate = self;
    source.backgroundColor = [UIColor whiteColor];
    [View addSubview:source];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 140, EMM_WIDTH, 20)];
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor colorFromHexCode:@"#5A5A5A"];
    label.text = @"按住录音";
    [View addSubview:label];
   
}
- (void)keyboardWasShown:(NSNotification*)aNotification {
    source.hidden = YES;
    NSInteger h = 0;
    if ([NSString isStringEmpty2:self.followId] == NO) {
        h = 140;
    }else {
        h = 100;
    }
    //键盘高度
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //    [_tableView setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];
    //表视图滚动至底部。
    [UIView animateWithDuration:0.5 animations:^{
        [_followTextField becomeFirstResponder];
//        _knowDtailTableView.frame = CGRectMake(0, -keyBoardFrame.size.height, EMM_WIDTH, EMM_HEIGHT-h-SafeAreaTopHeight);
        _followUpView.frame = CGRectMake(0,  EMM_HEIGHT-h-SafeAreaTopHeight-keyBoardFrame.size.height, EMM_WIDTH, h);
    }];
    
    
    //重新加载表视图
    //    [_tableView reloadData];
    
    
}



-(void)keyboardWillBeHidden:(NSNotification*)aNotification {
    source.hidden = YES;
    NSInteger h = 0;
    if ([NSString isStringEmpty2:self.followId] == NO) {
        h = 140;
    }else {
        h = 100;
    }
    _followUpView.frame = CGRectMake(0, EMM_HEIGHT-h-SafeAreaTopHeight, EMM_WIDTH, h);
    _knowDtailTableView.frame = CGRectMake(0, 120, EMM_WIDTH, EMM_HEIGHT-120-h-SafeAreaTopHeight);
    [_knowDtailTableView reloadData];
    
}


#pragma mark - 滑动窗口时，键盘隐藏
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    //直接调用隐藏键盘的方法即可
    [_followTextField resignFirstResponder];
    
}

#pragma mark - 未接通按钮
- (void)wjtBtnClick:(UIButton *)btn {
    [_followTextField resignFirstResponder];

    [self postEditFollowApi];
}


- (void)lyBtnClick:(UIButton *)btn {
    [_followTextField resignFirstResponder];
    if (_isly == YES) {
        NSInteger h = 0;
        if ([NSString isStringEmpty2:self.followId] == NO) {
            h = 140;
        }else {
            h = 100;
        }
        source.hidden = YES;
        _isly = NO;
        _followUpView.frame = CGRectMake(0, EMM_HEIGHT-SafeAreaTopHeight-h, EMM_WIDTH, h);
        _knowDtailTableView.frame =CGRectMake(0, 120, EMM_WIDTH, EMM_HEIGHT-120-h-SafeAreaTopHeight);
    }else {
        NSInteger h = 0;
        NSInteger h11 = 0;

        if ([NSString isStringEmpty2:self.followId] == NO) {
            h = 140+100+20;
            h11 = 140+10;
        }else {
            h = 100+100+20;
            h11 = 100+10;
        }
        UIView *v3 = [[UIView alloc] initWithFrame:CGRectMake(0, h11-10, EMM_WIDTH, 0.5)];
        v3.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [_followUpView addSubview:v3];
        
        _isly = YES;
        _followUpView.frame = CGRectMake(0, EMM_HEIGHT-SafeAreaTopHeight-h, EMM_WIDTH, h);
        _knowDtailTableView.frame =CGRectMake(0, 120, EMM_WIDTH, EMM_HEIGHT-120-h-SafeAreaTopHeight);
        source.hidden = NO;
    }
}

#pragma mark - InputFunctionViewDelegate
//上传文字
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message {
    
}
//上传图片
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendPicture:(UIImage *)image {
    
}

//上传声音
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendVoice:(NSData *)voice time:(NSInteger)second fielUrl:(NSString *)fielUrl {
    NSLog(@"%ld",second);
    NSLog(@"%ld",[voice length]);
    NSString *base64EncodedString = [NSString base64StringFromData:voice length:[voice length]];
    NSString *encodedImageStr = base64EncodedString;
    //-------------时间格式-----------
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"mm:ss"];
    NSDate  *date = [NSDate dateWithTimeIntervalSince1970:second];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];

    NSString *tmre = [NSString stringWithFormat:@"%@",currentDateStr];
    NSLog(@"%@",tmre);
    NSArray *arr = [tmre componentsSeparatedByString:@":"];
    NSString *newTmer = [NSString stringWithFormat:@"%@′%@″",arr[0],arr[1]];
    NSLog(@"%@",newTmer);
    NSArray *arrList = @[@{@"followContent":encodedImageStr}];
    [self postAddFollowApivoiceLocalAddrFollowType:@"3"
                                         imageType:nil
                                         voiceTime:newTmer
                                    voiceLocalAddr:fielUrl
                                            format:@".mp3"
                                       contentList:arrList];
}

- (void)xjBtnClick:(UIButton *)btn {
    [self showPhotosFromCamera];
}

- (void)xcBtnClick:(UIButton *)btn {
    [self showSelectPhotos];
}

#pragma mark - Path Utils
- (NSString *)cafPath
{
    NSString *cafPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Documents/play.caf"];
    return cafPath;
}

- (NSString *)mp3Path
{
    NSString *mp3Path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Documents/play.mp3"];
    return mp3Path;
}

-(void)initDataSource {
    titleDataArray = [[NSMutableArray alloc] initWithObjects:@"跟进记录", nil];
    grouparr0 = [[NSMutableArray alloc] initWithObjects:@"记录1",@"记录2",@"记录3",@"记录4",@"记录5", nil];
    [dic setValue:grouparr0 forKey:@"0"];
    selectedArr = [[NSMutableArray alloc] initWithObjects:@"0",nil];
}



#pragma mark - UITableView代理
//返回几个表头
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return titleDataArray.count;
}

//每一个表头下返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *string = [NSString stringWithFormat:@"%ld",section];
    if ([selectedArr containsObject:string]) {
        return _dataArr.count;
    }
    return 0;
}

//设置表头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

//Section Footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 5)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

//设置view，将替代titleForHeaderInSection方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, tableView.frame.size.width-20, 20)];
    titleLabel.text = [titleDataArray objectAtIndex:section];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = [UIColor colorFromHexCode:@"#1A1A1A"];
    [view addSubview:titleLabel];
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-20, 0.5)];
    lineImage.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, EMM_WIDTH, 50);
    button.tag = 100+section;
//    [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    view.backgroundColor = [UIColor colorFromHexCode:@"#fff5e9"];
    UILabel *sLabel6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 2, 30)];
    sLabel6.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
    [view addSubview:sLabel6];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-30, 15, 20, 20)];
    [view addSubview:imageView];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    FollowList *list = [_dataArr objectAtIndex:indexPath.row];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    if (list.contentList.count > 0) {
        for (ContentList *cList in list.contentList) {
            [arr addObject:cList];
        }
    }
    
    if (!([list.followType isEqualToString:@"2"] || [list.followType isEqualToString:@"3"])) {
        ContentList *cList = arr[0];
        NSInteger cellH = 0;
//        NSInteger h = [self textHeightFromTextString:cList.followContent width:[UIScreen mainScreen].bounds.size.width-115 fontSize:15]+30;
        NSInteger h = [IDTools textHeightFromTextString:cList.followContent width:[UIScreen mainScreen].bounds.size.width-115 fontSize:15]+30;
        if (h <= 70) {
            cellH = 70;
        }else {
            cellH = h;
        }        
        return cellH;
    }
    
    
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //直接调用隐藏键盘的方法即可
    [_followTextField resignFirstResponder];
    
//    NSString *indexStr = [NSString stringWithFormat:@"%ld",indexPath.section];
    FollowList *list = [_dataArr objectAtIndex:indexPath.row];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    if (list.contentList.count > 0) {
        for (ContentList *cList in list.contentList) {
            [arr addObject:cList];
        }
    }
    
    if ([list.followType isEqualToString:@"2"]) {
        static NSString *CellIdentifier = @"FollowThreeCellId";
        FollowThreeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FollowThreeCell" owner:self options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 59, EMM_WIDTH-20, 1)];
        lineImage.backgroundColor = [UIColor colorFromHexCode:@"#e4e4e4"];
//        [cell addSubview:lineImage];
        if (arr.count > 0) {
            ContentList *cList = arr[0];
            [cell.tpImageView sd_setImageWithURL:[NSURL URLWithString:cList.followContent] placeholderImage:nil];
            cell.tpTimerLabel.text = [NSString stringWithFormat:@"%ld",arr.count];
        }
        
        cell.tpTimerTwoLabel.text = list.followTime;
        cell.tpFollowModeTwoLabel.text = list.followMode;
        return cell;
    }else if ([list.followType isEqualToString:@"3"]) {
        static NSString *CellIdentifier = @"FollowTwoCellId";
        FollowTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FollowTwoCell" owner:self options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 59, EMM_WIDTH-20, 1)];
        lineImage.backgroundColor = [UIColor colorFromHexCode:@"#e4e4e4"];
//        [cell addSubview:lineImage];
        cell.timerTwoLabel.text = list.followTime;
        cell.followModeTwoLabel.text = list.followMode;
        cell.bfTimerLabel.text = [NSString stringWithFormat:@"%@",list.voiceTime];
        return cell;
    }
    static NSString *CellIdentifier = @"FollowOneCellId";
    FollowOneCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"FollowOneCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 59, EMM_WIDTH-20, 1)];
    lineImage.backgroundColor = [UIColor colorFromHexCode:@"#e4e4e4"];
//    [cell addSubview:lineImage];
    ContentList *cList = arr[0];
    cell.titleLabel.text = cList.followContent;
    cell.timerLabel.text = list.followTime;
    cell.followModeLabel.text = list.followMode;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArr.count > 0) {
        FollowList *list = [_dataArr objectAtIndex:indexPath.row];
        NSMutableArray *arrImageV = [[NSMutableArray alloc] init];
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        if (list.contentList.count > 0) {
            for (ContentList *cList in list.contentList) {
                [arr addObject:cList];
                [arrImageV addObject:cList.followContent];
            }
        }
        if ([list.followType isEqualToString:@"3"]) {
            NSString *url;
            for (int i = 0; i < arr.count; i++) {
                ContentList *cList = [arr objectAtIndex:i];
                url = cList.followContent;
            }
            
//            [[CustomPlayer sharedInstance] removeObserverAndNotification];
            
            [[CustomPlayer sharedInstance] setCustomPlayerStr:url];
            [[CustomPlayer sharedInstance] setCustomPlayerIsShowPlayView:^(BOOL isShow) {
                [[CustomPlayer sharedInstance] sourcePlay];
            }];
            
            [[CustomPlayer sharedInstance] setCustomPlayerShowFinish:^(NSString *timer) {
                NSLog(@"%@",timer);
                [[CustomPlayer sharedInstance] removeObserverAndNotification];
                [self creatPlayViewRemoveFromSuperview];
            }];
            
            _playView = [[PlayAnimationView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT)];
            _playView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
            [[UIApplication sharedApplication].keyWindow addSubview:_playView];
            __weak FollowUpViewController *weakMenuView = self;
            [_playView setPlayAnimationBlock:^{
//                [[CustomPlayer sharedInstance] sourceStop];
                [[CustomPlayer sharedInstance] removeObserverAndNotification];
                [weakMenuView creatPlayViewRemoveFromSuperview];
            }];

        }else if ([list.followType isEqualToString:@"2"]) {
            
            if (arrImageV.count > 0) {
                MHPhotoBrowserController *vc = [MHPhotoBrowserController new];
                NSMutableArray * bigImgArray = [NSMutableArray new];
                for (int i = 0; i < arrImageV.count; i++) {
                    NSString *url = [arrImageV objectAtIndex:i];
                    NSString *url1 = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    [bigImgArray addObject:[MHPhotoModel photoWithURL:[NSURL URLWithString:url1]]];
                }
                vc.currentImgIndex = 0;
                vc.displayTopPage = YES;
                vc.displayDeleteBtn = YES;
                vc.imgArray = bigImgArray;
                //        vc.isShouDel = 1;
                vc.displayDeleteBtn = NO;
                [self presentViewController:vc animated:YES completion:nil];
            }else {
                [self showToast:@"暂无图片预览"];
            }
        }
    }
}
//_playView
- (void)creatPlayViewRemoveFromSuperview {
    [_playView removeFromSuperview];
    _playView = nil;
}

-(void)doButton:(UIButton *)sender {
    NSString *string = [NSString stringWithFormat:@"%ld",sender.tag-100];
    if ([selectedArr containsObject:string]) {
        [selectedArr removeObject:string];
    } else  {
        [selectedArr addObject:string];
    }
    [_knowDtailTableView reloadData];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //开始编辑时触发，文本字段将成为first responder
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == _followTextField) {
        
        
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField.text.length > 0) {
        NSArray *arr = @[@{@"followContent":textField.text}];
        [self postAddFollowApivoiceLocalAddrFollowType:@"1"
                                             imageType:nil
                                             voiceTime:nil
                                        voiceLocalAddr:nil
                                                format:nil
                                           contentList:arr];
        _followTextField.text = nil;
    }
    [_followTextField resignFirstResponder];
    return YES;
}

#pragma mark -
- (void)postAddFollowApivoiceLocalAddrFollowType:(NSString *)followType
                                       imageType:(NSString *)imageType
                                       voiceTime:(NSString *)voiceTime
                                  voiceLocalAddr:(NSString *)voiceLocalAddr
                                          format:(NSString *)format
                                     contentList:(NSArray *)arr {
    [self showHudInWindow:@"正在加载请稍等..."];
//    [self hideHud];
    if ([NSString isStringEmpty2:self.followId] == NO) {
        followString = @"4";
    }
    AddFollowApi *api = [[AddFollowApi alloc] initWithFollowMode:followString
                                                      followType:followType
                                                       imageType:imageType
                                                       voiceTime:voiceTime
                                                  voiceLocalAddr:voiceLocalAddr
                                                     contentList:arr
                                                          format:format
                                                      customerId:_customerId
                                                        followId:self.followId];
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        AddFollowApi *result = (AddFollowApi *)request;
        if (result.isSuccess) {
//            [self hideHud];
//            [self showHudInWindow:@"正在加载请稍等..."];
            [self postGetFollowListApi];
            [_picArray removeAllObjects];
        } else {
            [self hideHud];
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 未接通Api
- (void)postEditFollowApi {
    [self showHudInWindow:@"正在加载中..."];
    EditFollowApi *api = [[EditFollowApi alloc] initWithFollowId:self.followId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        EditFollowApi *result = (EditFollowApi *)request;
        //请求成功
        if (result.isSuccess) {
            EditFollow *get = result.resultData;
            [self showToast:@"未接通，系统自动跟进一条记录"];
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - 调用系统相机和相册
////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark camera utility

////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable
{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable
{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos
{
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary
{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary
{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}


- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType
{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}


#pragma mark 1 拍照
- (void)showPhotosFromCamera
{
 
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
    } else {
        [self alertWithTitle:@"无法访问相机" msg:@"在\"设置>隐私>相机>Vgo\"中点击启用."];
    }
}

#pragma mark - UIImagePickerControllerDelegate
#pragma mark 2 拍照
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self showThisImagePicker:picker info:info];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}


#pragma mark 3 拍照
- (void)showThisImagePicker:(UIImagePickerController *)picker info:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
        
        if (imageData == NULL) {
            return;
        }
        
        NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
        NSString *encodedImageStr = base64EncodedString;
        NSArray *strarr  = [NSArray arrayWithObjects:@{@"followContent":encodedImageStr}, nil];
        [self postAddFollowApivoiceLocalAddrFollowType:@"2" imageType:@".png" voiceTime:nil voiceLocalAddr:nil format:nil contentList:strarr];
    }];
}



#pragma mark 照片
- (void)showSelectPhotos
{
    if (![self isPhotoLibraryAvailable]) {
        [self alertWithTitle:@"无法访问相机" msg:@"在\"设置>隐私>照片>Vgo\"中点击启用."];
        return;
    }
    QBImagePickerController *imagePickerController = [QBImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.showsNumberOfSelectedAssets = YES;
    imagePickerController.maximumNumberOfSelection = 5;
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}

#pragma mark - QBImagePickerControllerDelegate

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
    NSLog(@"Selected assets:");
    NSLog(@"%@", assets);// addbtn100
    for (ALAsset *result in assets) {
        // ALAsset的类型
        NSString *assetType = [result valueForProperty:ALAssetPropertyType];
        if ([assetType isEqualToString:ALAssetTypePhoto]){
            ALAssetRepresentation *assetRepresentation =[result defaultRepresentation];
            //            CGFloat imageScale = [assetRepresentation scale];
            UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];
            
            CGImageRef imageReference = [assetRepresentation fullResolutionImage];
            // 对找到的图片进行操作
            UIImage *image = [[UIImage alloc] initWithCGImage:imageReference scale:1.0 orientation:imageOrientation];
            if (image != nil){
                VGReturnGoodsPicDTO *v = [[VGReturnGoodsPicDTO alloc] init];
                v.picImage = image;
                v.asset = result;
                
                [_picArray addObject:v];
                
            } else {
                NSLog(@"Failed to create the image.");
            }
        }
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
    [self cat];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}


- (void)cat {
    NSMutableArray *strarr = nil;
    
    for (int i=0; i<_picArray.count; i++) {
        if (!strarr) {
            strarr = [NSMutableArray array];
        }
        
        VGReturnGoodsPicDTO *dto = [_picArray objectAtIndex:i];
        NSString *base64 = [self postImage:dto.picImage];
        [strarr addObject:@{@"followContent":base64}];
    }
    NSLog(@"%@",strarr);
    
    [self postAddFollowApivoiceLocalAddrFollowType:@"2" imageType:@".png" voiceTime:nil voiceLocalAddr:nil format:nil contentList:strarr];
}


- (NSString *)postImage:(UIImage *)portraitImg
{
    //    portraitImg = [portraitImg imageByScalingAndCroppingForSize:CGSizeMake(60, 60)];
    
    NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
    
    if (imageData == NULL) {
        return nil;
    }
    
    NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
    
    NSString *encodedImageStr = base64EncodedString;
    
    return encodedImageStr;
}

- (void)phoneSDetailsbtn:(UIButton *)sender {
//    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
//    NSString *isPhoneInformation = [userdf objectForKey:@"isPhoneInformation"];
//    if ([NSString isStringEmpty2:isPhoneInformation] == NO) {
//        if ([isPhoneInformation isEqualToString:@"0"]) {
//            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",self.mobile];
//            UIWebView * callWebview = [[UIWebView alloc] init];
//            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//            [self.view addSubview:callWebview];
//
//        }else if ([isPhoneInformation isEqualToString:@"1"]) {

//        }
//    }else {
//        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",self.mobile];
//        UIWebView * callWebview = [[UIWebView alloc] init];
//        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//        [self.view addSubview:callWebview];
//    }
    [self postGetUserCallListApi];

}

#pragma mark - 动态计算行高
- (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)textSize {
    CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:textSize]} context:nil];
    //返回计算出的行高
    return ceilf(rect.size.height);
}

- (void)postGetUserCallListApi {
    [self showHudInWindow:@"正在加载中..."];
    GetUserCallListApi *api = [[GetUserCallListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetUserCallListApi *result = (GetUserCallListApi *)request;
        //请求成功
        if (result.isSuccess) {
            GetUserCallList *get = result.resultData;
            
            if ([NSString isStringEmpty2:get.isPhoneInformation] == NO) {
                if ([get.isPhoneInformation isEqualToString:@"0"]) {
                    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",self.mobile];
                    UIWebView * callWebview = [[UIWebView alloc] init];
                    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                    [self.view addSubview:callWebview];
                }else {
                    UserCallMenuView *userListV = [[UserCallMenuView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT) title:@"选择拨打号码" nameArr:get.userCallList];
                    userListV.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
                    [[UIApplication sharedApplication].keyWindow addSubview:userListV];
                    __weak UserCallMenuView *weakMenuView = userListV;
                    [userListV setTouchUserCallMenuViewBlock:^(NSString *telePhone, NSString *telePhoneType) {
                        NSLog(@"%@-%@",telePhone,telePhoneType);
                        if ([NSString isStringEmpty2:telePhone] == NO) {
                            [self postGetCallBackApiTelePhoneString:telePhone];
                        }
                        [weakMenuView removeFromSuperview];
                    }];
                }
            }else {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",self.mobile];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }
        } else {
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

- (void)postGetCallBackApiTelePhoneString:(NSString *)telePhoneString {
    
    GetCallBackApi *api = [[GetCallBackApi alloc] initWithCustomerId:self.customerId caller:telePhoneString called:_getCustomerDetail.customerPhone terminalModel:@"0" terminalModelId:self.customerId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetCallBackApi *result = (GetCallBackApi *)request;
        //请求成功
        if (result.isSuccess) {
            GetCallBack *get = result.resultData;
            FollowUpViewController *fvc = [[FollowUpViewController alloc] init];
            fvc.customerId = self.customerId;
            fvc.followId = get.followId;
            [self.navigationController pushViewController:fvc animated:YES];
        } else {
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}



@end
